package cn.hhit.system.action;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import cn.dms.system.model.Department;
import cn.dms.system.service.DepartmentService;
import cn.hhit.common.action.CommonAction;
import cn.hhit.common.util.StringUtil;
import cn.hhit.system.model.RoleModel;
import cn.hhit.system.model.UserModel;
import cn.hhit.system.model.UserRole;
import cn.hhit.system.service.RoleService;
import cn.hhit.system.service.UserRoleService;
import cn.hhit.system.service.UserService;

public class LoginAction extends CommonAction {

	private static final long serialVersionUID = 8013816027944871760L;
	@Autowired
	@Qualifier("UserService")
	private UserService userService;
	@Autowired
	@Qualifier("RoleService")
	private RoleService roleService;
	@Autowired
	@Qualifier("UserRoleService")
	private UserRoleService userRoleService;
	@Autowired
	@Qualifier("DepartmentService")
	private DepartmentService schoolDeptService;
	private String username;
	private String password;

	@SuppressWarnings("unchecked")
	public void logon() throws Exception {
		if (null != username && null != password) {
			UserModel user = userService.getUnique(" where username=? and password=?", username, password);
			if (user != null) {
				session.put("uid", user.getId());
				session.put("username", user.getUsername());
				session.put("fullname", user.getName());
				session.put("password", user.getPassword());
				session.put("userid", user.getUnum());
				session.put("majorname", StringUtil.parseNULLtoString(user.getMajor()));
				session.put("deptname", StringUtil.parseNULLtoString(user.getDepartment()));
				Department sd = schoolDeptService.getUnique(" where deptname=?", user.getDepartment());
				if (sd != null) {
					session.put("deptid", StringUtil.parseNULLtoString(sd.getId()));
				}

				List<UserRole> urList = userRoleService.listByParams(" where userid=?", user.getId());
				List<String> rnames = new ArrayList<String>();
				List<Integer> rids = new ArrayList<Integer>();
				if (urList != null && !urList.isEmpty()) {
					for (UserRole ur : urList) {
						RoleModel r = roleService.get(ur.getRoleid());
						rnames.add(r.getName());
						rids.add(r.getId());
					}
				}
				session.put("roles", rnames.toString());
				session.put("roleids", rids.toString());
				writeResultToClient(response, true);
			} else {
				writeResultToClient(response, false);
			}
		} else {
			writeResultToClient(response, false);
		}
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getUsername() {
		return this.username;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getPassword() {
		return this.password;
	}
}